import java.applet.Applet;
import java.awt.Button;
import java.awt.Event;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


public class TestApplet extends Applet {

	@Override
	public void init() {
		super.init();
		setLayout(null);
		{
			final Button button = new Button("click");
			add(button);
			button.setSize(100, 26);
			button.setLocation(100, 100);
			button.setVisible(true);
			button.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					button.setLabel("HAHA");
					Socket socket = new Socket();
					try {
						socket.connect(new InetSocketAddress("127.0.0.1", 10190));
						System.out.println("connect");
						for(int i=0;i<20;i++)
						{
							socket.getOutputStream().write(("Hello"+i+"").getBytes());
							Thread.sleep(300);
						}
						System.out.println("Send");
					} catch (Exception err) {
						err.printStackTrace();
					}
				
				}
			});
		}
		{
			final Button button = new Button("Reuse");
			add(button);
			button.setSize(100, 26);
			button.setLocation(250, 100);
			button.setVisible(true);
			button.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					List<Thread> ts = new ArrayList<Thread>(20);
					for(int i=0;i<20;i++)
					{
						ts.add(new ClientThread(i+1));
					}
					for(Thread t:ts)
					{
						t.start();
					}
				
				}
			});
		}
		
		setSize(600, 400);
		setVisible(true);
	}
}

class ClientThread extends Thread
{
	int index = 0;
	public ClientThread(int index)
	{
		this.index = index;
	}
	
	@Override
	public void run() {
		final Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress("127.0.0.1", 10190));
			System.out.println("connect");
			socket.getOutputStream().write(("HelloWorld"+index+"\n").getBytes());
			//socket.getOutputStream().write("HelloWorld Again\n".getBytes());
			System.out.println("Send");
		} catch (IOException e2) {
			e2.printStackTrace();
		}
	}
}
